package org.example.tools;

import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Lists;
import lombok.Data;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

/**
 * @author weigang
 * @create 2022-10-27 16:21
 */
public class StreamUtils {
    public static <T> Stream<T> ofStream(Collection<T> col) {
        if (CollUtil.isEmpty(col)) {
            return Stream.empty();
        }

        return col.stream();
    }


    /**
     * 获取默认值
     */
    public static <T, R> R defaultIfNull(T target, Function<T, R> mapper, R defaultValue) {
        // Optional每次都会新建对象，不太适合简单场景
        if (Objects.isNull(target)) {
            return defaultValue;
        }

        return mapper.apply(target);
    }


    public static void main(String[] args) {

        @Data
        class School{
            Long schoolId;
            String schoolName;
        }


        School school1 = new School();
        school1.setSchoolId(1L);
        school1.setSchoolName("TJ University");
        School school2 = new School();
        school2.setSchoolId(1L);
        school2.setSchoolName("TJ2 University");
        Map<Long, School> schoolInfoMap = StreamUtils.ofStream(Lists.newArrayList(school1,school2))
                .collect(Collectors.toMap(School::getSchoolId, Function.identity(), (v1, v2) -> v1));
        System.out.println(schoolInfoMap);

        /*
        * v -> v ===  Function.identity()
        * 表示选择将原来的对象作为map的value值
        *  (v1, v2) -> v1 中，如果v1与v2的key值相同，选择v1作为那个key所对应的value值。
        * */

        School school = new School();
        school.setSchoolId(1L);
        school.setSchoolName("TJ University");
        StreamUtils.defaultIfNull(school, School::getSchoolName, "TG University");
        /*
        * Optional每次都会新建对象，不太适合简单场景
        * */
    }
}
